package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.consult.ConsultImgsEntity;
import com.hos.db.create.consult.ConsultTable;
import com.hos.db.create.user.UserDocTable;
import com.hos.db.create.user.UserPatTable;
import com.hos.db.entity.ArtEntity;
import com.hos.db.entity.consult.ConsultDocEntity;
import com.hos.db.entity.consult.ConsultEntity;
import com.hos.db.entity.consult.ConsultPatEntity;
import com.hos.net.req.consult.ConsultCreateReq;
import com.hos.net.req.consult.ConsultUpdateReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.operation.push.gtui.PushDoc;
import com.hos.operation.push.gtui.PushPat;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.JsonUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//咨询
public class ConsultManager {

    private static ConsultManager userPatsManager;

    public static ConsultManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new ConsultManager();
        }
        return userPatsManager;
    }

    //添加咨询
    public String onConsultAddReq(JdbcTemplate jdbcTemplate, String patId, ConsultCreateReq req) {
        String response = new MsgHint("添加失败").toJson();

        String sql = "INSERT INTO " + ConsultTable.tableName
                + "("
                + ConsultTable.tableConsultId + ","
                + ConsultTable.tableConsultTitle + ","
                + ConsultTable.tableConsultContent + ","
                + ConsultTable.tableConsultImages + ","
                + ConsultTable.tablePatId + ","
                + ConsultTable.tableDocId + ","
                + ConsultTable.tableConsulState + ","
                + ConsultTable.tableConsultUpdateTime + ","
                + ConsultTable.tableConsultCreateTime
                + ")"
                + " VALUES (?,?,?, ?, ?,?, ?,?,?)";

        try {
            Date time = new Date();
            String t1 = DateUtile.getDateFormat(time, DateUtile.DATA_FORMAT_YMD_HMS);
            String id = MD5Util.getMD5Format(patId + t1);
            int status = jdbcTemplate.update(sql,
                    new Object[]{id, req.consultTitle, req.consultMsg, JsonUtile.obj2Json(req.images),
                            patId, req.docId, 0, time, time});
            if (status > 0) {
                ConsultEntity consult = new ConsultEntity();
                consult.setConsultContent(req.consultMsg);
                consult.setConsultId(id);
                consult.setConsultCreateTime(time);
                consult.setConsultUpdateTime(time);
                consult.setConsultImages(req.consultMsg);
                consult.setConsultTitle(req.consultTitle);
                consult.setConsultState(0);
                BaseResponse res = new BaseResponse<ArtEntity>();
                res.obj = consult;
                response = res.toJson("0", "添加成功");
                //
                String pushId = DocsManager.getInstance().getPushId(jdbcTemplate, req.docId);
                PushDoc.getInstance().onConsultAdd( req.docId,pushId,
                        consult.getConsultId(),consult.getConsultContent(),"TEXT");
            }
        } catch (Exception e) {
            DLog.e("添加失败：" + e.getMessage());
        }
        return response;
    }

    //医生结束咨询
    public String onConsultEndReq(JdbcTemplate jdbcTemplate, String consultId, String patId) {
        String sql = "UPDATE " + ConsultTable.tableName
                + " SET "
                + ConsultTable.tableConsulState + " = '" + 2 + "', "
                + ConsultTable.tableConsultFinishTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'"
                + " WHERE "
                + ConsultTable.tableConsultId + " = '" + consultId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            String pushId = PatsManager.getInstance().getPushId(jdbcTemplate, patId);
            PushPat.getInstance().onConsultEnd(patId, pushId, consultId);
            return new MsgHint("0", "结束成功").toJson();
        }
        return new MsgHint("结束失败").toJson();
    }

    //回复咨询
    public String onConsultReplyReq(JdbcTemplate jdbcTemplate, String consultId) {
        String sql = "UPDATE " + ConsultTable.tableName
                + " SET "
                + ConsultTable.tableConsulState + " = '" + 1 + "', "
                + ConsultTable.tableConsultReplyTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'"
                + " WHERE "
                + ConsultTable.tableConsultId + " = '" + consultId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "结束成功").toJson();
        }
        return new MsgHint("结束失败").toJson();
    }

    //修改咨询状态
    public String onConsultUpdateReq(JdbcTemplate jdbcTemplate, String consultId, int state) {
        String sql = "UPDATE " + ConsultTable.tableName
                + " SET "
                + ConsultTable.tableConsulState + " = '" + state + "'"
                + " WHERE "
                + ConsultTable.tableConsultId + " = '" + consultId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //修改咨询
    public String onConsultUpdateReq(JdbcTemplate jdbcTemplate, ConsultUpdateReq req) {
        String update = "";
        String title = req.consultTitle;
        if (title != null && title != "") {
            update += " , " + ConsultTable.tableConsultTitle + " = '" + title + "'";
        }
        String msg = req.consultMsg;
        if (title != null && title != "") {
            update += " , " + ConsultTable.tableConsultContent + " = '" + msg + "'";
        }
        List<ConsultImgsEntity> images = req.images;
        if (images != null) {
            update += " , " + ConsultTable.tableConsultImages + " = '" + JsonUtile.obj2Json(images) + "'";
        }
        if (update.equals("")) {
            return new MsgHint("请设置要修改的参数").toJson();
        }
        update = update.replaceFirst(" , ", "");
        update += " , " + ConsultTable.tableConsultUpdateTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'";
        //
        String sql = "UPDATE " + ConsultTable.tableName
                + " SET "
                + update
                + " WHERE "
                + ConsultTable.tableConsultId + " = '" + req.consultId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //删除
    public String onConsultDeleteReq(JdbcTemplate jdbcTemplate, String id) {

        String sql = "DELETE  FROM " + ConsultTable.tableName
                + " WHERE "
                + ConsultTable.tableConsultId + " = '" + id + "'";
        int state = jdbcTemplate.update(sql);
        if (state == 0) {
            return new MsgHint("咨询不存在").toJson();
        }
        return new MsgHint("0", "删除成功").toJson();
    }

    /**
     * 获取咨询
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<ConsultEntity> onConsults(JdbcTemplate jdbcTemplate, String docId, String patId,
                                          int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String w = "";
        if (patId != null && patId != "") {
            w = " WHERE "
                    + ConsultTable.tablePatId + " = '" + patId + "'";
        }
        if (docId != null && docId != "") {
            w = " WHERE "
                    + ConsultTable.tableDocId + " = '" + docId + "'";
        }
        String sql = "SELECT * FROM " + ConsultTable.tableName
                + w
                + " ORDER BY " + ConsultTable.tableConsultUpdateTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<ConsultEntity> cons = onQuery(jdbcTemplate, sql);
        if (cons == null) {
            cons = new ArrayList();
        }
        return cons;
    }

    /**
     * 患者获取咨询
     *
     * @param jdbcTemplate
     * @param pageSize     type 0新咨询 1：已回答 2：已结束
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<ConsultDocEntity> onPatConsults(JdbcTemplate jdbcTemplate, String patId, int type, int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String and = "";
        String order = "";
        switch (type) {
            case 0:
                //新咨询
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultUpdateTime + " DESC ";
                break;
            case 1:
                //已回答
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultReplyTime + " DESC ";
                break;
            case 2:
                //已结束
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultFinishTime + " DESC ";
                break;
        }
        //
        String sql = "SELECT "
                + "r." + ConsultTable.tableConsultId
                + " ,r." + ConsultTable.tablePatId
                + " ,r." + ConsultTable.tableDocId
                + " ,r." + ConsultTable.tableConsulState
                + " ,r." + ConsultTable.tableConsultFinishTime
                + " ,r." + ConsultTable.tableConsultReplyTime
                + " ,r." + ConsultTable.tableConsultCreateTime
                + " ,r." + ConsultTable.tableConsultUpdateTime
                + " ,r." + ConsultTable.tableConsultContent
                + " ,r." + ConsultTable.tableConsultImages
                + " ,r." + ConsultTable.tableConsultTitle
                //
                + " ,d." + UserDocTable.tableDocName
                + " ,d." + UserDocTable.tableDocPortrait
                //
                + " from "
                + ConsultTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserDocTable.tableName + " d "
                + " on "
                + "r." + ConsultTable.tableDocId
                + " = "
                + "d." + UserDocTable.tableDocId
                + " WHERE "
                + "r." + ConsultTable.tablePatId + " = '" + patId + "'"
                + and
                + order
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<ConsultDocEntity> cons = onQueryDoc(jdbcTemplate, sql);
        if (cons == null) {
            cons = new ArrayList();
        }
        return cons;
    }

    /**
     * 医生获取咨询
     * 1
     *
     * @param jdbcTemplate
     * @param pageSize     type 0新咨询 1：已回答 2：已结束
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<ConsultPatEntity> onDocConsults(JdbcTemplate jdbcTemplate, String docId, int type, int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String and = "";
        String order = "";
        switch (type) {
            case 0:
                //新咨询
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultUpdateTime + " DESC ";
                break;
            case 1:
                //已回答
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultReplyTime + " DESC ";
                break;
            case 2:
                //已结束
                and = " and " + ConsultTable.tableConsulState + " = '" + type + "' ";
                order = "  ORDER BY " + ConsultTable.tableConsultFinishTime + " DESC ";
                break;
        }
        //
        String sql = "SELECT "
                + "r." + ConsultTable.tableConsultId
                + " ,r." + ConsultTable.tablePatId
                + " ,r." + ConsultTable.tableDocId
                + " ,r." + ConsultTable.tableConsulState
                + " ,r." + ConsultTable.tableConsultFinishTime
                + " ,r." + ConsultTable.tableConsultReplyTime
                + " ,r." + ConsultTable.tableConsultCreateTime
                + " ,r." + ConsultTable.tableConsultUpdateTime
                + " ,r." + ConsultTable.tableConsultContent
                + " ,r." + ConsultTable.tableConsultImages
                + " ,r." + ConsultTable.tableConsultTitle
                //
                + " ,d." + UserPatTable.tablePatName
                + " ,d." + UserPatTable.tablePatPortrait
                + " ,d." + UserPatTable.tablePatIdentityNumber
                //
                + " from "
                + ConsultTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserPatTable.tableName + " d "
                + " on "
                + "r." + ConsultTable.tablePatId
                + " = "
                + "d." + UserPatTable.tablePatId
                + " WHERE "
                + "r." + ConsultTable.tableDocId + " = '" + docId + "'"
                + and
                + order
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<ConsultPatEntity> cons = onQueryPat(jdbcTemplate, sql);
        if (cons == null) {
            cons = new ArrayList();
        }
        return cons;
    }

    /**
     * 医生获取咨询
     *
     * @param jdbcTemplate
     * @param consultId    咨询id
     */
    public String onDocConsultsReq(JdbcTemplate jdbcTemplate, String consultId) {
        //
        String sql = "SELECT "
                + "r." + ConsultTable.tableConsultId
                + " ,r." + ConsultTable.tablePatId
                + " ,r." + ConsultTable.tableDocId
                + " ,r." + ConsultTable.tableConsulState
                + " ,r." + ConsultTable.tableConsultFinishTime
                + " ,r." + ConsultTable.tableConsultReplyTime
                + " ,r." + ConsultTable.tableConsultCreateTime
                + " ,r." + ConsultTable.tableConsultUpdateTime
                + " ,r." + ConsultTable.tableConsultContent
                + " ,r." + ConsultTable.tableConsultImages
                + " ,r." + ConsultTable.tableConsultTitle
                //
                + " ,d." + UserPatTable.tablePatName
                + " ,d." + UserPatTable.tablePatPortrait
                + " ,d." + UserPatTable.tablePatIdentityNumber
                //
                + " from "
                + ConsultTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserPatTable.tableName + " d "
                + " on "
                + "r." + ConsultTable.tablePatId
                + " = "
                + "d." + UserPatTable.tablePatId
                + " WHERE "
                + "r." + ConsultTable.tableConsultId + " = '" + consultId + "'";

        List<ConsultPatEntity> cons = onQueryPat(jdbcTemplate, sql);

        if (cons != null && cons.size() > 0) {
            ConsultPatEntity consultPatEntity = cons.get(0);

            BaseResponse baseRes = new BaseResponse();
            baseRes.obj = consultPatEntity;
            return baseRes.toJson("0", "");

        }

        return new MsgHint("获取失败").toJson();
    }

    /**
     * 患者获取咨询
     *
     * @param jdbcTemplate
     * @param consultId    咨询id
     */
    public String onPatConsultsReq(JdbcTemplate jdbcTemplate, String consultId) {
        //
        String sql = "SELECT "
                + "r." + ConsultTable.tableConsultId
                + " ,r." + ConsultTable.tablePatId
                + " ,r." + ConsultTable.tableDocId
                + " ,r." + ConsultTable.tableConsulState
                + " ,r." + ConsultTable.tableConsultFinishTime
                + " ,r." + ConsultTable.tableConsultReplyTime
                + " ,r." + ConsultTable.tableConsultCreateTime
                + " ,r." + ConsultTable.tableConsultUpdateTime
                + " ,r." + ConsultTable.tableConsultContent
                + " ,r." + ConsultTable.tableConsultImages
                + " ,r." + ConsultTable.tableConsultTitle
                + " ,r." + ConsultTable.tableConsultImages
                //
                + " ,d." + UserDocTable.tableDocName
                + " ,d." + UserDocTable.tableDocPortrait
                //
                + " from "
                + ConsultTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserDocTable.tableName + " d "
                + " on "
                + "r." + ConsultTable.tableDocId
                + " = "
                + "d." + UserDocTable.tableDocId
                + " WHERE "
                + "r." + ConsultTable.tableConsultId + " = '" + consultId + "'";

        List<ConsultDocEntity> cons = onQueryDoc(jdbcTemplate, sql);

        if (cons != null && cons.size() > 0) {
            ConsultDocEntity consultPatEntity = cons.get(0);

            BaseResponse baseRes = new BaseResponse();
            baseRes.obj = consultPatEntity;
            return baseRes.toJson("0", "");

        }

        return new MsgHint("获取失败").toJson();
    }

    //咨询
    private List<ConsultPatEntity> onQueryPat(JdbcTemplate jdbcTemplate, String sql) {
        List<ConsultPatEntity> cons = null;
        try {
            cons = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(ConsultPatEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return cons;
    }

    //咨询
    private List<ConsultDocEntity> onQueryDoc(JdbcTemplate jdbcTemplate, String sql) {
        List<ConsultDocEntity> cons = null;
        try {
            cons = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(ConsultDocEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return cons;
    }

    //咨询
    private List<ConsultEntity> onQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<ConsultEntity> cons = null;
        try {
            cons = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(ConsultEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return cons;
    }

}
